"""
交互式叙事代理
负责将故事内容转换为交互式HTML页面
"""

from pathlib import Path
from typing import List, Dict, Optional
import json
from datetime import datetime


class InteractiveNarrativeAgent:
    """交互式叙事代理 - 生成交互式HTML故事页面"""
    
    def __init__(self, output_dir: Path, theme: str = "default"):
        """
        Args:
            output_dir: 输出目录
            theme: 页面主题 (default/dark/fantasy/scifi)
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.theme = theme
        self.themes = self._init_themes()
    
    def _init_themes(self) -> Dict:
        """初始化主题配置"""
        return {
            'default': {
                'primary_color': '#667eea',
                'secondary_color': '#764ba2',
                'bg_gradient': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                'card_bg': 'white',
                'text_color': '#333'
            },
            'dark': {
                'primary_color': '#1a1a2e',
                'secondary_color': '#16213e',
                'bg_gradient': 'linear-gradient(135deg, #0f0c29, #302b63, #24243e)',
                'card_bg': 'rgba(255,255,255,0.05)',
                'text_color': '#eee'
            },
            'fantasy': {
                'primary_color': '#8e44ad',
                'secondary_color': '#e74c3c',
                'bg_gradient': 'linear-gradient(135deg, #8e44ad 0%, #e74c3c 100%)',
                'card_bg': 'white',
                'text_color': '#333'
            },
            'scifi': {
                'primary_color': '#00d4ff',
                'secondary_color': '#0066ff',
                'bg_gradient': 'linear-gradient(135deg, #000428 0%, #004e92 100%)',
                'card_bg': 'rgba(0,212,255,0.05)',
                'text_color': '#00d4ff'
            }
        }
    
    def generate_interactive_story(self, 
                                   pages: List[str],
                                   title: str,
                                   visualizations: Optional[List[Dict]] = None,
                                   choices: Optional[Dict] = None,
                                   metadata: Optional[Dict] = None) -> str:
        """
        生成交互式故事HTML
        
        Args:
            pages: 故事页面列表
            title: 故事标题
            visualizations: 可视化数据 (来自 data_visualization_agent)
            choices: 选择分支 {page_index: [{'text': str, 'goto': int}]}
            metadata: 元数据 (作者、日期等)
        
        Returns:
            生成的HTML文件路径
        """
        # 文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{title}_{timestamp}.html"
        output_path = self.output_dir / filename
        
        # 生成HTML
        html_content = self._create_html(pages, title, visualizations, choices, metadata)
        
        # 保存
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"\n✅ 交互式故事已生成: {output_path}")
        return str(output_path)
    
    def _create_html(self, pages, title, visualizations, choices, metadata) -> str:
        """创建HTML内容"""
        theme = self.themes.get(self.theme, self.themes['default'])
        
        # 转换为JSON
        pages_json = json.dumps(pages, ensure_ascii=False)
        viz_json = json.dumps(visualizations or [], ensure_ascii=False)
        choices_json = json.dumps(choices or {}, ensure_ascii=False)
        
        # 生成HTML
        html = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Microsoft YaHei', sans-serif;
            background: {theme['bg_gradient']};
            color: {theme['text_color']};
            min-height: 100vh;
            padding: 20px;
            line-height: 1.8;
        }}
        
        .container {{
            max-width: 900px;
            margin: 0 auto;
        }}
        
        .story-title {{
            text-align: center;
            font-size: 3em;
            margin-bottom: 30px;
            animation: fadeInDown 1s ease;
        }}
        
        .progress-container {{
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: rgba(0,0,0,0.1);
            z-index: 1000;
        }}
        
        .progress-bar {{
            height: 100%;
            background: linear-gradient(90deg, {theme['primary_color']}, {theme['secondary_color']});
            width: 0%;
            transition: width 0.3s ease;
        }}
        
        .page-card {{
            background: {theme['card_bg']};
            border-radius: 20px;
            padding: 40px;
            margin: 30px 0;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            opacity: 0;
            transform: translateY(30px);
            transition: all 0.6s ease;
        }}
        
        .page-card.visible {{
            opacity: 1;
            transform: translateY(0);
        }}
        
        .page-number {{
            display: inline-block;
            background: {theme['primary_color']};
            color: white;
            padding: 8px 20px;
            border-radius: 20px;
            font-size: 0.9em;
            margin-bottom: 20px;
            font-weight: 600;
        }}
        
        .page-content {{
            font-size: 1.3em;
            line-height: 2;
            margin: 25px 0;
            text-align: justify;
        }}
        
        .chart-container {{
            margin: 30px 0;
            padding: 25px;
            background: rgba(255,255,255,0.05);
            border-radius: 15px;
        }}
        
        .choices {{
            display: flex;
            gap: 15px;
            margin-top: 30px;
            flex-wrap: wrap;
        }}
        
        .choice-btn {{
            flex: 1;
            min-width: 200px;
            padding: 15px 30px;
            background: linear-gradient(135deg, {theme['primary_color']}, {theme['secondary_color']});
            color: white;
            border: none;
            border-radius: 50px;
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            font-weight: 600;
        }}
        
        .choice-btn:hover {{
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }}
        
        .navigation {{
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
            gap: 15px;
        }}
        
        .nav-btn {{
            padding: 15px 35px;
            background: {theme['card_bg']};
            color: {theme['primary_color']};
            border: 2px solid {theme['primary_color']};
            border-radius: 30px;
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
        }}
        
        .nav-btn:hover:not(:disabled) {{
            background: {theme['primary_color']};
            color: white;
            transform: scale(1.05);
        }}
        
        .nav-btn:disabled {{
            opacity: 0.3;
            cursor: not-allowed;
        }}
        
        @keyframes fadeInDown {{
            from {{
                opacity: 0;
                transform: translateY(-30px);
            }}
            to {{
                opacity: 1;
                transform: translateY(0);
            }}
        }}
    </style>
</head>
<body>
    <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
    </div>
    
    <div class="container">
        <h1 class="story-title">{title}</h1>
        
        <div id="storyContent"></div>
        
        <div class="navigation">
            <button class="nav-btn" id="prevBtn">← 上一页</button>
            <button class="nav-btn" id="nextBtn">下一页 →</button>
        </div>
    </div>
    
    <script>
        const storyData = {pages_json};
        const vizData = {viz_json};
        const choicesData = {choices_json};
        
        let currentPage = 0;
        
        function init() {{
            renderPage(currentPage);
            updateProgress();
            
            document.getElementById('prevBtn').addEventListener('click', () => navigatePage(-1));
            document.getElementById('nextBtn').addEventListener('click', () => navigatePage(1));
            
            document.addEventListener('keydown', (e) => {{
                if (e.key === 'ArrowLeft') navigatePage(-1);
                if (e.key === 'ArrowRight') navigatePage(1);
            }});
        }}
        
        function renderPage(pageIndex) {{
            const container = document.getElementById('storyContent');
            container.innerHTML = '';
            
            const pageCard = document.createElement('div');
            pageCard.className = 'page-card';
            
            const pageNumber = document.createElement('div');
            pageNumber.className = 'page-number';
            pageNumber.textContent = `第 ${{pageIndex + 1}} / ${{storyData.length}} 页`;
            pageCard.appendChild(pageNumber);
            
            const content = document.createElement('div');
            content.className = 'page-content';
            content.textContent = storyData[pageIndex];
            pageCard.appendChild(content);
            
            // 渲染可视化
            if (vizData.length > 0) {{
                const viz = vizData.find(v => v.page_index === pageIndex);
                if (viz) {{
                    const chartContainer = document.createElement('div');
                    chartContainer.className = 'chart-container';
                    const canvas = document.createElement('canvas');
                    canvas.id = 'chart_' + pageIndex;
                    chartContainer.appendChild(canvas);
                    pageCard.appendChild(chartContainer);
                    
                    setTimeout(() => renderChart(viz, canvas.id), 300);
                }}
            }}
            
            // 渲染选择
            if (choicesData[pageIndex]) {{
                const choicesDiv = document.createElement('div');
                choicesDiv.className = 'choices';
                
                choicesData[pageIndex].forEach(choice => {{
                    const btn = document.createElement('button');
                    btn.className = 'choice-btn';
                    btn.textContent = choice.text;
                    btn.addEventListener('click', () => {{
                        currentPage = choice.goto;
                        renderPage(currentPage);
                        updateProgress();
                        window.scrollTo({{ top: 0, behavior: 'smooth' }});
                    }});
                    choicesDiv.appendChild(btn);
                }});
                
                pageCard.appendChild(choicesDiv);
            }}
            
            container.appendChild(pageCard);
            setTimeout(() => pageCard.classList.add('visible'), 100);
            
            document.getElementById('prevBtn').disabled = pageIndex === 0;
            document.getElementById('nextBtn').disabled = pageIndex === storyData.length - 1;
        }}
        
        function renderChart(vizData, canvasId) {{
            const ctx = document.getElementById(canvasId).getContext('2d');
            
            new Chart(ctx, {{
                type: vizData.chart_type || 'bar',
                data: {{
                    labels: vizData.data.labels,
                    datasets: [{{
                        label: vizData.title,
                        data: vizData.data.values,
                        backgroundColor: [
                            'rgba(102, 126, 234, 0.8)',
                            'rgba(118, 75, 162, 0.8)',
                            'rgba(46, 204, 113, 0.8)',
                            'rgba(241, 196, 15, 0.8)',
                            'rgba(231, 76, 60, 0.8)'
                        ]
                    }}]
                }},
                options: {{
                    responsive: true,
                    animation: {{ duration: 2000 }}
                }}
            }});
        }}
        
        function navigatePage(direction) {{
            const newPage = currentPage + direction;
            if (newPage >= 0 && newPage < storyData.length) {{
                currentPage = newPage;
                renderPage(currentPage);
                updateProgress();
                window.scrollTo({{ top: 0, behavior: 'smooth' }});
            }}
        }}
        
        function updateProgress() {{
            const progress = ((currentPage + 1) / storyData.length) * 100;
            document.getElementById('progressBar').style.width = progress + '%';
        }}
        
        init();
    </script>
</body>
</html>'''
        
        return html


# 便捷函数
def create_interactive_html(pages: List[str], 
                           title: str,
                           output_dir: Path,
                           visualizations: List[Dict] = None,
                           theme: str = "default") -> str:
    """
    快速创建交互式HTML的便捷函数
    
    Example:
        >>> create_interactive_html(
        ...     pages=["第一页内容", "第二页内容"],
        ...     title="我的故事",
        ...     output_dir=Path("interactive_stories"),
        ...     theme="fantasy"
        ... )
    """
    agent = InteractiveNarrativeAgent(output_dir, theme)
    return agent.generate_interactive_story(pages, title, visualizations)